package com.cardvalue.sys.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.cardvalue.sys.R;
import com.cardvalue.sys.activity.ConfirmListActivity;
import com.cardvalue.sys.base.BaseFragment;
import com.cardvalue.sys.code.CallBackCode;
import com.cardvalue.sys.entity.Apply;
import com.cardvalue.sys.entity.PostCreateAuth;
import com.cardvalue.sys.entity.VerifyImgCode;
import com.cardvalue.sys.mode.Service;
import com.cardvalue.sys.mode.UserService;
import com.cardvalue.sys.tool.CheckingForm;
import com.cardvalue.sys.tool.LocationUtil;
import com.cardvalue.sys.tool.MessageBox;
import com.cardvalue.sys.tool.Utiltools;

import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.fraudmetrix.android.FMAgent;
import io.realm.Realm;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * 绑卡界面  对公
 * Created by Administrator on 2016/6/13.
 */
public class BankCardFragment extends BaseFragment{
    @Bind( R.id.open_name) EditText secondaryBankAcctName;          // 开户名称(放款)（对公）
    @Bind( R.id.open_bank) TextView secondaryBankName;              // 开户银行   (放款)账户信息(对公)secondaryBankName
    @Bind( R.id.bank_account) EditText secondaryBankDDA;            // 银行账号(放款)
    @Bind( R.id.account_name) EditText directDebitAcctName ;        // 还款账户名(还款)
    @Bind( R.id.account_cardid)  EditText directDebitAcctId;        // 身份证(还款)
    @Bind( R.id.open_bank_person)  TextView directDebitBankName;    // 开户银行(还款)个人
    @Bind( R.id.bank_account_person)  EditText directDebitAcctNo;   // 银行账号(还款)
    @Bind( R.id.bank_account_number) EditText directDebitAcctPhone; // 银行预留手机号
    @Bind( R.id.bank_getCode) Button bank_getCode;               	// 获取验证码按钮
    @Bind( R.id.credit_authorization) CheckBox credit_authorization; // 融资协议授权
    @Bind( R.id.bank_account_code)  EditText mobilePhoneVerifyCode;  // 银行验证码
    @Bind( R.id.bind_buttons)  Button 	bind_buttons;               // 绑定银行卡
    @Bind( R.id.bank_tk3) TextView bank_tk3;               			// 融资协议页面

    private String smsNumber ="";  //这是发送短信的手机号码
    private String  imageVerifyCode;//用户输入的图形验证码
    private Service.GetImgCode  VerifyImgCodeService;//获取图形验证码
    private Timer timer=new Timer(); // 控制获取验证码按钮是否显示
    public static boolean isRefrensh = true;//判断是否可以弹出dialog
    private int codeExpirDate = 0;  // 验证码有效期
    private String  verifyCode =""; // 手机验证码
    private Realm realm;
    private Retrofit retrofit;
    public static Handler handler;
    private String secondaryBankABA;    //secondaryBankName 开户银行   2    还款账户信息(对公)
    private String  directDebitBankCode; //(对公)放款  1
    private UserService   userService;

    private  String  msecondaryBankAcctName;
    private  String  msecondaryBankName;
    private  String  msecondaryBankDDA;
    private  String  mdirectDebitAcctName;
    private  String  mdirectDebitAcctId;
    private  String  mdirectDebitBankName;
    private  String  mdirectDebitAcctNo;
    private  String  mdirectDebitAcctPhone;
    private  String   mmobilePhoneVerifyCode;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.bank_card_base,container,false);
        ButterKnife.bind(this,view);
        userService=new UserService(getActivity());
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what== CallBackCode.CALLBACK_MSG_GETBANK_PRIVATE){//选择银行卡
                    Bundle bundle=msg.getData();
                    secondaryBankName.setText(bundle.get("title").toString().trim());
                    secondaryBankABA=bundle.get("id").toString().trim();
                }else if(msg.what==CallBackCode.CALLBACK_MSG_GETBANK_PUBLIC){//选择银行卡
                    Bundle bundle=msg.getData();
                    directDebitBankName.setText(bundle.get("title").toString().trim());
                    directDebitBankCode=bundle.get("id").toString().trim();
                }
            }
        };
        return view;
    }


    @OnClick({R.id.open_bank,R.id.open_bank_person,R.id.bind_buttons,R.id.bank_getCode}) void click(View viwe){
        switch (viwe.getId()){
            case R.id.open_bank:	// 开户银行   2    还款账户信息(对公)
                Intent intentBank=new Intent(getActivity(), ConfirmListActivity.class) ;
                if(secondaryBankName.getText().toString().trim().toString().equals("")){
                    intentBank.putExtra("title","");
                    intentBank.putExtra("type","2");
                    intentBank.putExtra("tagName","secondaryBankName");
                    startActivity(intentBank);
                    return;
                }else{
                    intentBank.putExtra("title",secondaryBankName.getText().toString());
                    intentBank.putExtra("type","2");
                    intentBank.putExtra("tagName","secondaryBankName");
                    startActivity(intentBank);
                }
                break;
            case R.id.open_bank_person:  //(对公)放款  1
                Intent intentdirectDebitBank=new Intent(getActivity(), ConfirmListActivity.class) ;
                if(directDebitBankName.getText().toString().trim().toString().equals("")){
                    intentdirectDebitBank.putExtra("title","");
                    intentdirectDebitBank.putExtra("type","1");
                    intentdirectDebitBank.putExtra("tagName","secondaryBankName1");
                    startActivity(intentdirectDebitBank);
                    return;
                }else{
                    intentdirectDebitBank.putExtra("title",directDebitBankName.getText().toString());
                    intentdirectDebitBank.putExtra("type","1");
                    intentdirectDebitBank.putExtra("tagName","secondaryBankName1");
                    startActivity(intentdirectDebitBank);
                }
                break;
            case R.id.bank_getCode://点击验证码按钮
                getImage();
                break;
            case R.id.bind_buttons://点击提交按钮
                   msecondaryBankAcctName=secondaryBankAcctName.getText().toString();
                   msecondaryBankName=secondaryBankName.getText().toString();
                   msecondaryBankDDA=secondaryBankDDA.getText().toString();
                   mdirectDebitAcctName=directDebitAcctName.getText().toString();
                   mdirectDebitAcctId=directDebitAcctId.getText().toString();
                   mdirectDebitBankName=directDebitBankName.getText().toString();
                   mdirectDebitAcctNo=directDebitAcctNo.getText().toString();
                   mdirectDebitAcctPhone=directDebitAcctPhone.getText().toString();
                   mmobilePhoneVerifyCode=mobilePhoneVerifyCode.getText().toString();
                if(!CheckingForm.checkForBankPublic(msecondaryBankAcctName, msecondaryBankName,
                        msecondaryBankDDA,mdirectDebitAcctName,  mdirectDebitAcctId,
                        mdirectDebitBankName,directDebitBankCode,  secondaryBankABA,
                        mdirectDebitAcctNo,  mdirectDebitAcctPhone,  mmobilePhoneVerifyCode)){
                    MessageBox.ToastShow(CheckingForm.LastError,getActivity());
                    return;
                }else{
                    //先授权
                    PostCreateAuth task=new PostCreateAuth();
                    String blackBox = FMAgent.onEvent();
                    Map<String, String> map= LocationUtil.getMap();
                    task.setTime(new Date().toLocaleString() );
                    task.setIpAddress("");//IP地址
                    task.setBlackBox(blackBox);
                    task.setDeviceNumber(map.get("imel")==null?"":map.get("imel").toString());
                    task.setGps(map.get("ongitude")+","+map.get("atitude"));
                    WebView webview = new WebView(getActivity());
                    webview.layout(0, 0, 0, 0);
                    WebSettings settings = webview.getSettings();
                    String ua = settings.getUserAgentString();
                    task.setAgent(ua);
                    task.setType(Integer.parseInt("6"));
                    userService.getUserCreateAuthService(task, new UserService.GetPostCreateAuthCallback() {
                        @Override
                        public void success(PostCreateAuth task) {
                            updata();
                        }

                        @Override
                        public void fail(PostCreateAuth task) {

                        }

                        @Override
                        public void cancelDialog() {

                        }
                    });

                }
                break;
        }

    }

    // 更新申请
    public void updata(){
        Apply apply=new Apply();
        apply.setSecondaryBankABA(secondaryBankABA);
        apply.setSecondaryBankDDA(msecondaryBankDDA);
        apply.setSecondaryBankName(msecondaryBankName);
        apply.setSecondaryBankAcctName(msecondaryBankAcctName);
        apply.setDirectDebitBankCode(directDebitBankCode.trim());
        apply.setDirectDebitAcctName(mdirectDebitAcctName);
        apply.setDirectDebitAcctId(mdirectDebitAcctId);
        apply.setDirectDebitBankName(mdirectDebitBankName);
        apply.setDirectDebitAcctNo(mdirectDebitAcctNo);
        apply.setDirectDebitAcctPhone(mdirectDebitAcctPhone);
        apply.setMobilePhoneVerifyCode(mmobilePhoneVerifyCode);
        userService.GetUpdateApplication(apply, new UserService.GetApplyCallback() {
            @Override
            public void success(Apply apply) {

            }

            @Override
            public void fail(String msg) {

            }

            @Override
            public void cancelDialog() {

            }
        });
    }



    /**
     * 获取图形验证码
     */
    public void getImage(){
        if(TextUtils.isEmpty(bank_getCode.getText().toString().trim())){
            MessageBox.ToastShow("请输入手机号", getActivity());
            return;
        }
        //发送获取验证码的请求
        VerifyImgCodeService=retrofit.create(Service.GetImgCode.class);
        VerifyImgCode verifyImgCode=new VerifyImgCode();
        smsNumber=bank_getCode.getText().toString();
        verifyImgCode.setMobilePhone(smsNumber);
        Utiltools.printE("第二次的时候是否有值：",imageVerifyCode+"hah");
        if(!TextUtils.isEmpty(imageVerifyCode)){
            verifyImgCode.setImageVerifyCode(imageVerifyCode);
        }
        Call<VerifyImgCode> repos = VerifyImgCodeService.attemptVerifyImgCode(verifyImgCode);
        repos.enqueue(new Callback<VerifyImgCode>() {
            @Override
            public void onResponse(Call<VerifyImgCode> call, Response<VerifyImgCode> response) {
                VerifyImgCode verifyImgCode=response.body();
                String error=verifyImgCode.getError()+"";
                Utiltools.printE("验证码失败后的==11=",verifyImgCode.getImgUrl()+"===url==");
                Utiltools.printE("验证码失败后的==11=",verifyImgCode.getError()+""+"===url==");
                if(!error.equals("null")){
                    MessageBox.ToastShow(verifyImgCode.getError()+"",getActivity());
                    isRefrensh=true;
                    imageVerifyCode="";
                    return;
                }
                /**
                 * 先判断url有没有值,如果url没有值，那就说明是第二次调用，是手机验证码
                 */
                if(verifyImgCode.getImgUrl()==null){
                    MessageBox.ToastShow("验证码已发送，请注意查收",getActivity());
                    codeExpirDate = 60; // 验证码的有效时间
                    verifyCode = "code"; // 标记已发验证码
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            updateVerifyCode();
                        }
                    },0,1000);
                }else{
                    /**
                     * 这里面又要判断dialog，是不是已经弹出来，
                     * 如果已经弹出来的话，就只要更新url中的图片
                     */
                    Utiltools.printE("验证码失败后的===",verifyImgCode.getImgUrl()+"===url==");
                    if(isRefrensh){
                        MessageBox.EditAlertReg(getActivity(),verifyImgCode.getImgUrl(),dialog,bank_getCode.getText().toString().trim(),handler);
                    }else{
                        MessageBox.setVerifyCode(getActivity(),verifyImgCode.getImgUrl());
                    }
                }
            }

            @Override
            public void onFailure(Call<VerifyImgCode> call, Throwable t) {

            }
        });
    }



    /**
     * 获取验证码倒计时
     */
    public void updateVerifyCode(){
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (codeExpirDate==0){
                    bank_getCode.setText("获取验证码");
                    bank_getCode.setEnabled(true);            //	设置按钮恢复
                    timer.cancel();                      //	取消定时器
                    timer = new Timer();
                }else{
                    if (bank_getCode.isEnabled())
                        bank_getCode.setEnabled(false);
                    bank_getCode.setText("验证码("+codeExpirDate+"秒)");
                    codeExpirDate--;
                }
            }
        });
    }

}
